##########################################
## Copyright 2012-2013 Ceruti Francesco & contributors
##
## This file is part of LiSP (Linux Show Player).
##########################################

import socket
import threading


class Master:

    def __init__(self, masterPort, slavePort):
        self.slavePort = slavePort
        self.slave = []
        self.sSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sSocket.bind(('', masterPort))
        self.sSocket.listen(16)
        self.acceptThread = threading.Thread(target=self.listen)
        self.acceptThread.setDaemon(True)
        self.acceptThread.start()

    def listen(self):
        while(True):
            try:
                conn, addr = self.sSocket.accept()
                data = conn.recv(1024)
                if(data == bytes('SLAVE', 'UTF-8')):
                    self.slave.append(addr[0])
                conn.close()
            except:
                pass

    def sendAction(self, action):
        for sl in self.slave:
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.connect((sl, self.slavePort))
                sock.send(bytes(action, 'UTF-8'))
                sock.close()
            except:
                self.slave.remove(sl)
